package com.ruoyi.web.controller.system;

import java.util.Base64;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.MessagePayload;
import cn.wildfirechat.pojos.MultiMessageResult;
import cn.wildfirechat.sdk.MessageAdmin;
import cn.wildfirechat.sdk.messagecontent.FileMessageContent;
import cn.wildfirechat.sdk.messagecontent.ImageMessageContent;
import cn.wildfirechat.sdk.messagecontent.SoundMessageContent;
import cn.wildfirechat.sdk.messagecontent.VideoMessageContent;
import cn.wildfirechat.sdk.model.IMResult;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.GroupAssistantMessageHistory;
import com.ruoyi.system.domain.SendHistory;
import com.ruoyi.system.domain.vo.MessageQuery;
import com.ruoyi.system.domain.vo.UserSendGroupMessageVo;
import com.ruoyi.system.dto.GroupAssistantMessageHistoryDTO;
import com.ruoyi.system.dto.GroupSendMessage;
import com.ruoyi.system.dto.TMessagesDTO;
import com.ruoyi.system.imDomain.TextMessageContent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TMessages;
import com.ruoyi.system.service.ITMessagesService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 消息Controller
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@RestController
@RequestMapping("/system/messages")
@Api(tags = "消息")
public class TMessagesController extends BaseController
{
    @Autowired
    private ITMessagesService tMessagesService;

    /**
     * 查询消息列表
     */
    @GetMapping("/list")
    @ApiOperation("消息列表")
    @Anonymous
    public TableDataInfo list(MessageQuery query) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        return tMessagesService.selectTMessagesList(query, pageNum, pageSize);
    }

    /**
     * 查询用户消息列表
     */
//    @PreAuthorize("@ss.hasPermi('system:messages:list')")
    @GetMapping("/user/list")
    @ApiOperation("用户消息列表")
    @Anonymous
    public TableDataInfo userList(MessageQuery query)
    {
        // 使用高效的分表分页查询
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();

        return tMessagesService.selectTMessagesListWithPaging(query, pageNum, pageSize);
    }

    /**
     * 导出消息列表
     */
    @Log(title = "消息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MessageQuery query)
    {
        // 使用高效的分表分页查询
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        TableDataInfo tableDataInfo = tMessagesService.selectTMessagesListWithPaging(query, pageNum, pageSize);
        List<TMessagesDTO> rows = (List<TMessagesDTO>) tableDataInfo.getRows();
        ExcelUtil<TMessagesDTO> util = new ExcelUtil<>(TMessagesDTO.class);
        util.exportExcel(response, rows, "消息数据");
    }

    /**
     * 获取消息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:messages:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tMessagesService.selectTMessagesById(id));
    }

    /**
     * 新增消息
     */
    @PreAuthorize("@ss.hasPermi('system:messages:add')")
    @Log(title = "消息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMessages tMessages)
    {
        return toAjax(tMessagesService.insertTMessages(tMessages));
    }

    /**
     * 修改消息
     */
    @PreAuthorize("@ss.hasPermi('system:messages:edit')")
    @Log(title = "消息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMessages tMessages)
    {
        return toAjax(tMessagesService.updateTMessages(tMessages));
    }

    /**
     * 删除消息
     */
    @Log(title = "消息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tMessagesService.deleteTMessagesByIds(ids));
    }



    /**
     * 广播消息
     */
    @Log(title = "广播消息", businessType = BusinessType.DELETE)
	@PostMapping("/broadcastMessage")
    @ApiOperation("广播消息")
    @Anonymous
    public AjaxResult broadcastMessage(@RequestBody String text)
    {
        return toAjax(tMessagesService.broadcastMessage(text));
    }

    /**
     * 广播消息
     */
    @Log(title = "广播消息历史消息", businessType = BusinessType.DELETE)
	@PostMapping("/broadcastMessageList")
    public TableDataInfo broadcastMessageList()
    {
        startPage();
        List<SendHistory> list = tMessagesService.broadcastMessageList();
        return getDataTable(list);

    }

    /**
     * 群发消息
     */
    @Log(title = "群发消息", businessType = BusinessType.DELETE)
    @PostMapping("/sendGroupMessage")
    public AjaxResult sendGroupMessage(@RequestBody GroupSendMessage message)
    {
        return toAjax(tMessagesService.groupMessage(message));
    }
    /**
     * 群发消息记录列表
     */
    @Log(title = "群发消息记录列表", businessType = BusinessType.DELETE)
    @GetMapping("/sendGroupMessage/list")
    public TableDataInfo sendGroupMessageList()
    {
        startPage();
        List<SendHistory> list = tMessagesService.sendGroupMessageList();
        return getDataTable(list);
    }

    @PostMapping("/userSendGroupMessage")
    @ApiOperation("群发助手功能")
    @Anonymous
    public AjaxResult userSendGroupMessage(@RequestBody UserSendGroupMessageVo message)
    {
        System.out.println("群助手消息：===="+message.toString());
        try {
            MessagePayload messagePayload;
            switch (message.getType()){
                case "1":
                    TextMessageContent textMessageContent = new TextMessageContent(message.getText());
                    messagePayload = textMessageContent.encode();
                    break;
                case "2":
                    SoundMessageContent soundMessageContent = new SoundMessageContent();
                    soundMessageContent.setRemoteMediaUrl(message.getText());
                    if (message.getDuration() != null){
                        //时长，单位秒
                        soundMessageContent.setDuration(message.getDuration().intValue());
                    }
                    messagePayload = soundMessageContent.encode();
                    break;
                case "3":
                    ImageMessageContent imageMessageContent = new ImageMessageContent();
                    if (StringUtils.isNotEmpty(message.getThumbnailBase64edData())){
                        imageMessageContent.setThumbnailBytes(Base64.getDecoder().decode(message.getThumbnailBase64edData()));
                    }
                    //图片地址，发送前需要先上传到对象存储服务。
                    imageMessageContent.setRemoteMediaUrl(message.getText());
                    //消息转成Payload并发送
                    messagePayload = imageMessageContent.encode();
                    break;
                case "5":
                    //测试发送文件消息
                    FileMessageContent fileMessageContent = new FileMessageContent();
                    if (StringUtils.isNotEmpty(message.getFileName())){
                        //设置文件名
                        fileMessageContent.setName(message.getFileName());
                    }
                   if (message.getFileSize() != null){
                       //设置文件大小
                       fileMessageContent.setSize(message.getFileSize());
                   }
                    //设置文件链接
                    fileMessageContent.setRemoteMediaUrl(message.getText());
                    //消息转成Payload并发送
                    messagePayload = fileMessageContent.encode();
                    break;
                case "6":
                    VideoMessageContent videoMessageContent = new VideoMessageContent();
                    if (StringUtils.isNotEmpty(message.getThumbnailBase64edData())){
                        //base64edData为视频的首帧的缩略图。缩略图的生成规则是，把图片压缩到120X120大小的方框内，45%的质量压缩为JPG格式，再把二进制做base64编码得到字符串。
                        videoMessageContent.setThumbnailBytes(Base64.getDecoder().decode(message.getThumbnailBase64edData()));
                    }
                    if (message.getDuration() != null){
                        //视频时长，单位秒
                        videoMessageContent.setDuration(message.getDuration());
                    }
                    //视频地址，发送前需要先上传到对象存储服务。
                    videoMessageContent.setRemoteMediaUrl(message.getText());
                    //消息转成Payload并发送
                    messagePayload = videoMessageContent.encode();
                    break;
                default:
                    throw new RuntimeException("不支持的消息类型");
            }
            IMResult<MultiMessageResult> result = MessageAdmin.multicastMessage(message.getUserId(), message.getUserIds(), 0,messagePayload );
            if (result != null && result.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                System.out.println("multi message success, messageid is " + result.getResult().getMessageUid());
                // 保存发送记录
                GroupAssistantMessageHistory history = new GroupAssistantMessageHistory();
                history.setSenderId(message.getUserId());
                history.setReceiverIds(String.join(",", message.getUserIds()));
                history.setMessageContent(message.getText());
                history.setMessageType(message.getType());
                long messageUid = result.getResult().getMessageUid();
                history.setMessageId(String.valueOf(messageUid));
                tMessagesService.insertGroupAssistantMessageHistory(history);
                return success();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return error();
    }


    @GetMapping("/getUserSendGroupMessageHistory/{id}")
    @ApiOperation("群发助手功能消息历史记录")
    @Anonymous
    public AjaxResult getUserSendGroupMessageHistory(@PathVariable String id)  {
        List<GroupAssistantMessageHistoryDTO> dtos = tMessagesService.getGroupAssistantMessageHistory(id);
        for (GroupAssistantMessageHistoryDTO dto : dtos) {
            String[] split = dto.getReceiverIds().split(",");
            dto.setReceiverIdsNum(split.length);
            dto.setReceiverIdsByInfo(tMessagesService.getUserNameByUserIds(split));
        }
        return success(dtos);
    }


    @GetMapping("/deleteHistory/{id}")
    @ApiOperation("删除群发助手功能消息历史记录")
    @Anonymous
    public AjaxResult deleteHistory(@PathVariable String id)  {
        return toAjax(tMessagesService.deleteGroupAssistantMessageHistory(id));
    }
}
